package com.example.flyway.controller;

//import com.example.flyway.properties.FlywayProperties;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.MigrationInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

@RestController
@RequestMapping(value = "/api/zz/flyway")
public class FlywayController {

    public static Flyway flyway;

    //@Autowired
    //private FlywayProperties flywayProperties;
    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void init() {
        flyway = new Flyway();
        flyway.setDataSource(dataSource);

        //flywayProperties.setDataSource(dataSource);
    }

    /**
     * 迁移
     * @return 数量
     */
    @RequestMapping(value = "/migrate", method = RequestMethod.GET)
    @ResponseBody
    public Integer migrate() {
        //System.out.println(flywayProperties.getBaselineDescription());
        return flyway.migrate();
    }

    /**
     * 清除
     * @return 是否成功
     */
    @RequestMapping(value = "/clean", method = RequestMethod.GET)
    @ResponseBody
    public Boolean clean() {
        flyway.clean();
        return Boolean.TRUE;
    }

    /**
     * 信息
     * @return 信息
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public MigrationInfo[] info() {
        MigrationInfoService service = flyway.info();
        return service.all();
    }

    /**
     * 修复
     * @return 是否成功
     */
    @RequestMapping(value = "/repair", method = RequestMethod.GET)
    @ResponseBody
    public Boolean repair() {
        flyway.repair();
        return Boolean.TRUE;
    }

    /**
     * 验证
     * @return 是否成功
     */
    @RequestMapping(value = "/validate", method = RequestMethod.GET)
    @ResponseBody
    public Boolean validate() {
        flyway.validate();
        return Boolean.TRUE;
    }

    /**
     * 基线
     * @return 是否成功
     */
    @RequestMapping(value = "/baseline", method = RequestMethod.GET)
    @ResponseBody
    public Boolean baseline() {
        flyway.baseline();
        return Boolean.TRUE;
    }

    /**
     * 回退
     * @return 数量
     */
    @RequestMapping(value = "/undo", method = RequestMethod.GET)
    @ResponseBody
    public Integer undo() {
        return flyway.undo();
    }

}
